package com.ojoin.trade.supplyloan_core.web.controller;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ojoin.trade.common.constdef.IConstDef;
import com.ojoin.trade.common.exception.BusinessException;
import com.ojoin.trade.common.utils.CommonUtils;
import com.ojoin.trade.common.utils.DownloadUtils;
import com.ojoin.trade.common.utils.LogUtils;
import com.ojoin.trade.common.utils.TimeUtils;
import com.ojoin.trade.common.web.controller.BaseControllerImpl;
import com.ojoin.trade.common.web.domain.Result;
import com.ojoin.trade.common.web.domain.Result.Status;
import com.ojoin.trade.common.web.domain.SessionUser;
import com.ojoin.trade.common.web.service.BaseService;
import com.ojoin.trade.common_core.web.domain.TbMerchantUser;
import com.ojoin.trade.common_core.web.service.MerchantUserBaseService;
import com.ojoin.trade.supplyloan_core.constdef.ISLConstDef;
import com.ojoin.trade.supplyloan_core.web.domain.TbSlLoanApplication;
import com.ojoin.trade.supplyloan_core.web.domain.TbSlLoanApplicationInfoVO;
import com.ojoin.trade.supplyloan_core.web.service.TbSlLoanApplicationService;
import com.ojoin.trade.supplyloan_core.web.service.TbSlLoanCreditService;
import com.ojoin.trade.supplyloan_core.web.service.TbSlLoanService;


@Controller
@RequestMapping("/slloan")
public class SlLoanApplicationController extends BaseControllerImpl<TbSlLoanApplicationInfoVO>{
	 
	private Logger log=LoggerFactory.getLogger(SlLoanApplicationController.class);
	@Autowired
	private TbSlLoanApplicationService liveservice;

	@Autowired
	private TbSlLoanCreditService creditservice;
	
	public TbSlLoanApplicationService getLiveservice() {
		return liveservice;
	} 
	
	/**
	 * 
	 * 用户提交实名信息  
	 * @param request
	 * @return
	 */
	
	@ResponseBody
	@RequestMapping(value = "/uploadrealname", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
	public Result uploadRealName(HttpServletRequest request) {
		int liveid = -1;
		try {   
              int joinuserid=CommonUtils.getSessionUser(request).getId();
              TbSlLoanApplication vo = liveservice.queryTbSlApplicationByJoinId(joinuserid);
              if (vo == null) {
            	  vo = new TbSlLoanApplication();
            	  vo.setLoanstatus(ISLConstDef.SLLOANSTATUS_REALNAME);
            	  vo.setIdOfTbMerchantUser(joinuserid);
            	  liveid = liveservice.insert(vo);
              } else {
            	  liveid = vo.getId();
            	  liveservice.updateLoanStatusByIdWithTs(liveid, joinuserid, ISLConstDef.SLLOANSTATUS_REALNAME, TimeUtils.getDateString(vo.getRowUpdateTime()));  
              }
               
              return new Result(Status.OK, liveid);    
		} catch (Exception e) {
			log.error("九盈用户id"+liveid+"提交实名认证信息报错", e);
			if (e instanceof BusinessException)
				return new Result(Status.ERROR, e.getMessage());
			 
			return new Result(Status.ERROR, "九盈用户id"+liveid+"提交实名认证信息报错，请重试");
		}
	}
	
	
	/**
	 * 
	 * 用户提交上下游合同
	 * @param request
	 * @return
	 */
	
	@ResponseBody
	@RequestMapping(value = "/uploadcontract", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
	public Result uploadContract(HttpServletRequest request, String contractFilePath) {
		int joinuserid=CommonUtils.getSessionUser(request).getId();
		try {   
              liveservice.updateContract(joinuserid, contractFilePath);
              return new Result(Status.OK, joinuserid);    
		} catch (Exception e) {
			log.error("九盈用户id"+joinuserid+"提交上下游合同报错", e);
			if (e instanceof BusinessException)
				return new Result(Status.ERROR, e.getMessage());
			 
			return new Result(Status.ERROR, "九盈用户id"+joinuserid+"提交上下游合同报错，请重试");
		}
	}
	
	/**
	 * 
	 * 用户提交模糊授信资料
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/uploadCreditInformation", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
	public Result uploadCreditInformation(HttpServletRequest request, String creditInformation) {
		int joinuserid=CommonUtils.getSessionUser(request).getId();
		try {   
              liveservice.updateCreditInformation(joinuserid, creditInformation);
              return new Result(Status.OK, joinuserid);    
		} catch (Exception e) {
			log.error("九盈用户id"+joinuserid+"提交模糊授信资料报错", e);
			if (e instanceof BusinessException)
				return new Result(Status.ERROR, e.getMessage());
			 
			return new Result(Status.ERROR, "九盈用户id"+joinuserid+"提交模糊授信资料报错，请重试");
		}
	}
	
	 
    @ResponseBody
    @RequestMapping(value = "/getexpiredays",method = RequestMethod.GET)
    public Result  getExpireDays(HttpServletRequest request){
        try{
            int joinuserid=CommonUtils.getSessionUser(request).getId();
            Long days=liveservice.getCreditExpireDays(joinuserid);
            return new Result(Status.OK,days);
        }catch (Exception e){
            log.error("查询授信到期日失败",e);
            if(e instanceof BusinessException){
                return  new Result(Status.ERROR,e.getMessage());
            }
            return new Result(Status.ERROR,"查询用户的授信到期日有误");
        }
    }
	
	@Override
	protected BaseService<TbSlLoanApplicationInfoVO> getBaseService() {
		return null;
	}
	
	@Autowired
	private TbSlLoanService loanService;
	
	@Autowired
	private MerchantUserBaseService userService;
	
    @ResponseBody
	@RequestMapping(value = "/downloadSLCheckAccountFile", method = RequestMethod.GET)
	public void downloadSLCheckAccountFile( HttpServletRequest request, HttpServletResponse response) throws IOException {
		SessionUser uservo = CommonUtils.getSessionUser(request);
    	ByteArrayOutputStream bos = new ByteArrayOutputStream();
    	loanService.exportSLLoanReportExcelFile(uservo.getId(), bos);
    	TbMerchantUser muservo = userService.queryById(uservo.getId());
    	String filename = muservo.getShortname() + "供应链贷（对账表-" + TimeUtils.getCurDate() + "）.xls";
    	DownloadUtils.download(request,response,filename,bos.toByteArray());
		LogUtils.info(log, "下载%s",IConstDef.DOWNLOAD_LOANCHECKACCOUNT);
	}
    
    @ResponseBody
    @RequestMapping(value = "/selectNotcompleteCreditLoanByJoinid",method = RequestMethod.GET)
    public Result  selectNotcompleteCreditLoanByJoinid(HttpServletRequest request){
        try{
            int joinuserid=CommonUtils.getSessionUser(request).getId();
            String count = creditservice.selectNotcompleteCreditLoanByJoinid(joinuserid);
            return new Result(Status.OK, CommonUtils.getInt(count));
        }catch (Exception e){
            log.error("查询未完成的融资申请记录失败",e);
            if(e instanceof BusinessException){
                return  new Result(Status.ERROR,e.getMessage());
            }
            return new Result(Status.ERROR,"查询未完成的融资申请记录有误");
        }
    }
    
}
